<template>
  <div>
    <div>基础版</div>
    <div id="canvasTap" style="padding: 20px 0">修改canvas大小</div>

    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const width = 500;
    const height = 300;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(-100, 300, 300);
    camera.lookAt(scene.position);
    const render = new THREE.WebGLRenderer();
    render.setSize(width, height);
    // console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    //   几何体
    const geometry = new THREE.BoxGeometry(50, 50, 50);
    //   材质
    const material = new THREE.MeshLambertMaterial({
      color: '#0021da',
      transparent: true,
      opacity: 0.9,
    });

    const materialMesh = new THREE.Mesh(geometry, material);
    materialMesh.position.set(25, 25, 25);
    scene.add(materialMesh);

    const num = 1000; //控制长方体模型数量
    for (let i = 0; i < num; i++) {
      const geometry = new THREE.BoxGeometry(5, 5, 5);
      const material = new THREE.MeshLambertMaterial({
        color: 0x00ffff,
      });
      const mesh = new THREE.Mesh(geometry, material);
      // 随机生成长方体xyz坐标
      const x = (Math.random() - 0.5) * 200;
      const y = (Math.random() - 0.5) * 200;
      const z = (Math.random() - 0.5) * 200;
      mesh.position.set(x, y, z);
      scene.add(mesh); // 模型对象插入场景中
    }

    function renderFun() {
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();

    // 跟新画布大小
    function updateCanvas() {
      console.log('跟新画布大小');

      // 重置渲染器输出画布canvas尺寸
      render.setSize(800, 500);
      // 全屏情况下：设置观察范围长宽比aspect为窗口宽高比
      camera.aspect = 800 / 500;
      // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
      // 但是不会每渲染一帧，就通过相机的属性计算投影矩阵(节约计算资源)
      // 如果相机的一些属性发生了变化，需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
      camera.updateProjectionMatrix();
    }
    document.getElementById('canvasTap')?.addEventListener('click', updateCanvas);
  }
</script>
